var COS = require('cos-js-sdk-v5');
var SecretId = 'AKIDdIpDShEnBa1KUYcZLwJUwCKMNBmAMNCt'
var SecretKey = 'fATZSN8rX2QdeTBkIlS6mS0Le9YmmmdH'
var cos = new COS({
	SecretId: SecretId, // 推荐使用环境变量获取；用户的 SecretId，建议使用子账号密钥，授权遵循最小权限指引，降低使用风险。子账号密钥获取可参考https://cloud.tencent.com/document/product/598/37140
	SecretKey: SecretKey, // 推荐使用环境变量获取；用户的 SecretKey，建议使用子账号密钥，授权遵循最小权限指引，降低使用风险。子账号密钥获取可参考https://cloud.tencent.com/document/product/598/37140
})


function uploadFilePromise(blob, fileName) {
	const picOperations = JSON.stringify({
		is_pic_info: 0, // 固定
		// fileid 设置和Key相同可实现只保留处理后的图片而不保留原图
		rules: [{
			fileid: encodeURIComponent(fileName),
			rule: 'imageMogr2/format/webp/interlace/0'
		}],
	});
	return new Promise(function(resolve, reject) {
		cos.putObject({
			Bucket: 'hl-1316403513',
			Region: 'ap-shanghai',
			Key: fileName,
			Body: blob,
			Headers: {
				// 'Pic-Operations': picOperations,
			},

		}, function(err, data) {
			console.log(err || data);
			if (err) {
				console.log('上传失败', err);
				resolve({
					url: data.Location,
					status: 'failed'
				})
			} else {
				resolve({
					url: data.Location,
					status: 'success'
				})
			}
		});
	})
}
//转换图片格式
function objectURLToBlob(blodurl, fileName) {
	return new Promise((resolve, reject) => {
		var http = new XMLHttpRequest();
		http.open('GET', blodurl, true);
		http.responseType = 'blob';
		http.onload = function(e) {
			if (this.status == 200 || this.status ===
				0) { // console.log('blod数据',this.response);									// 在将blod数据转为file
				let files = new window.File([this.response], fileName, {
					type: 'image'
				});
				resolve(files);
			} else {
				reject(e)
			}
		};
		http.send();
	})
}
//随机图片名字,防止重复替换cos图片
function uuid() {
	const tempUrl = URL.createObjectURL(new Blob());
	const uuid = tempUrl.toString();
	URL.revokeObjectURL(tempUrl); // 释放这个url
	return uuid.substring(uuid.lastIndexOf("/") + 1)
}

export default {
	uploadFilePromise,
	objectURLToBlob,
	uuid,
}